package com.sun.tspalgorithm.entity;

import com.sun.tspalgorithm.util.DistanceUtil;
import lombok.Data;

import java.util.ArrayList;

@Data
public class Tour {

    // 访问路线，保存需要访问的城市，数组
    private ArrayList<City> tour = new ArrayList<>();

    // 构建一个空的路线
    public Tour() {
        for (int i = 0; i < CityManager.numberOfCities(); i++) {
            tour.add(null);
        }
    }

    // 用路线tour构建当前路线
    public Tour(ArrayList<City> tour) {
        this.tour = (ArrayList<City>) tour.clone();
    }

    // 返回当前路线信息
    public ArrayList<City> getTour() {
        return tour;
    }

    // 创建一个城市路线
    public void generateIndividual() {
        // 将目的城市一个个添加到当前路线中
        for (int cityIndex = 0; cityIndex < CityManager.numberOfCities(); cityIndex++) {
            setCity(cityIndex, CityManager.getCity(cityIndex));
        }
    }

    // 从当前路线中获取指定位置的城市
    public City getCity(int tourPosition) {
        return (City) tour.get(tourPosition);
    }

    // 将一个目的城市放置到当前路线的指定位置
    public void setCity(int tourPosition, City city) {
        tour.set(tourPosition, city);
    }

    // 获得当前路线上所有城市距离的总和
    public Double getDistance() {
        Double tourDistance = 0.00;
        for (int cityIndex = 0; cityIndex < tourSize(); cityIndex++) {
            City fromCity = getCity(cityIndex);
            City destinationCity;
            if (cityIndex + 1 < tourSize()) {
                destinationCity = getCity(cityIndex + 1);
            } else {
//                destinationCity = getCity(0);
                break;
            }
            tourDistance += DistanceUtil.getDistance(fromCity, destinationCity);
        }
        return tourDistance;
    }

    // 获得路线上城市的数量
    public int tourSize() {
        return tour.size();
    }

    @Override
    public String toString() {
        String geneString = "";
        for (int i = 0; i < tourSize(); i++) {
            if (i == tourSize() - 1) {
                geneString += getCity(i);
                break;
            }
            geneString += getCity(i) + "=>";
        }
        return geneString;
    }

}
